<?php
require_once("../../config/config.inc.php");
require_once($CFG_REAL_CLASSES."/json.class.php");
$json = new Services_JSON();

$sEPID   = $SEC->sCorpCD;
$sRole   = $SEC->sRole;
$sAction = fn_getParam("strAction","");
$sMark   = "";
$sRelation = 1; //同一单位成员

if ($sAction=="USER_LIST") {
    $iStart = fn_getParam("start","0");
    $iPageSize = fn_getParam("limit","20");
    $sUserName     = fn_getParam("strUserName","");
    $sTrueName     = fn_getParam("strTrueName","");
    $sSex          = fn_getParam("strSex","");
    $sRight        = fn_getParam("strRight","");
    $sLockStatus   = fn_getParam("strLockStatus","");
    $sPetName      = fn_getParam("strPetName","");
    
    $aLockStatus = $DICT->getDictArray1("BASE_LOCKSTATUS",true,array('1'));
    ////get user info
    $sqlWhere = "FROM $TABLE_EP_USER WHERE EPID='".$sEPID."' ";
    if ($sUserName != "") {
        $sqlWhere.= "AND USERNAME LIKE '%".$sUserName."%' ";
    }
    if ($sTrueName != "") {
        $sqlWhere.= "AND TRUENAME LIKE '%".$sTrueName."%' ";
    }
    if ($sPETNAME != "") {
        $sqlWhere.= "AND PETNAME LIKE '%".$sPetName."%' ";
    }
    if ($sSex != "") {
        $sqlWhere.= "AND SEX='".$sSex."' ";
    }
    if ($sRight != "") {
        $sqlWhere.= "AND RIGHTLEVEL='".$sRight."' ";
    }
    $iRowCount = $DB->getFirstField("SELECT COUNT(1) ".$sqlWhere);

    $sql = "SELECT ID,EPID,USERNAME,TRUENAME,PETNAME,HEADIMAGE,DEPARTMENT,TITLE,SEX,";
    $sql.= "HOMEADDRESS,POSTCODE,HOMEPHONE,MOBILEPHONE,QQNUMB,MSN,EMAIL,RIGHTLEVEL,";
    $sql.= "REGDATE,HITS,LOCKSTATUS,SECURITY ";
    $sql.= $sqlWhere ." LIMIT $iStart,$iPageSize";
    //echo "sql:".$sql;
    $stmt= $DB->query($sql);
    $iIndex = 0;
    while ($row = $DB->fetchRow($stmt)) {
        $aUser[$iIndex] = array(
            "sID"=>$row["ID"],"uName"=>$row["USERNAME"],"tName"=>$row["TRUENAME"],
            "pName"=>$row["PETNAME"],"sSex"=>($row["SEX"]=="male"?"男性":"女性"),
            "sDept"=>$row["DEPARTMENT"],"sTitle"=>$row["TITLE"],
            "hAdd"=>$row["HOMEADDRESS"],"pCode"=>$row["POSTCODE"],
            "hPhone"=>$row["HOMEPHONE"],"mPhone"=>$row["MOBILEPHONE"],
            "qNumb"=>$row["QQNUMB"],"sMsn"=>$row["MSN"],
            "eMail"=>$row["EMAIL"],"sRight"=>($row["RIGHTLEVEL"]=='admin'?'管理员':'普通用户'),
            "sLock"=>$aLockStatus[$row["LOCKSTATUS"]],"cDate"=>$row["REGDATE"]);
        if ($sRole == RIGHT_USER) { //not admin
            $sSECURITY = fn_str_split($row["SECURITY"]);
            if (!fn_getSecViewRight($sSECURITY[1],$sRelation)) {
                $aUser[$iIndex]["hAdd"] = $sMark; //add. and postcode
                $aUser[$iIndex]["pCode"]= $sMark;
            }
            if (!fn_getSecViewRight($sSECURITY[2],$sRelation)) $aUser[$iIndex]["hPhone"] = $sMark; //联系电话
            if (!fn_getSecViewRight($sSECURITY[3],$sRelation)) $aUser[$iIndex]["mPhone"] = $sMark; //手机号码
            if (!fn_getSecViewRight($sSECURITY[4],$sRelation)) $aUser[$iIndex]["qNumb"] = $sMark; //QQ号码
            if (!fn_getSecViewRight($sSECURITY[5],$sRelation)) $aUser[$iIndex]["sMsn"]  = $sMark; //MSN ADD.
            if (!fn_getSecViewRight($sSECURITY[6],$sRelation)) $aUser[$iIndex]["eMail"] = $sMark; //EMAIL ADD.
        }
        $iIndex++;
    }
    $DB->freeResult($stmt);
    if (count($aUser[0])>0) {
        echo $json->encode(array('success'=>true,'total'=>$iRowCount,'data'=>$aUser));
    } else {
        echo $json->encode(array('success'=>true,'total'=>"0",'data'=>""));
    }
    unset($aUser);
    return;
} else 
if ($sAction=='SysImage') {
    $node = isset($_REQUEST['node']) ? $_REQUEST['node']:".";
    if (strpos($node, '..') !== false) {
        return false;
    }
    $newPath = $CFG_REAL_IMAGES_USER.'/'.$node;
    if (!is_dir($newPath)) return false;
    
    $nodes = array();
    $d = dir($newPath);
    while ($f = $d->read()){
        if ($f == '.' || $f == '..' || substr($f, 0, 1) == '.') continue;
        if (is_dir($newPath.'/'.$f)) {
            $nodes[] = array('text'=>$f, 'id'=>$node.'/'.$f, 'qtip'=>'', 'cls'=>'folder');
        } else if (preg_match('/\.(jpg|jpeg|gif|png)$/', $f)) {
            $nodes[] = array('text'=>$f, 'id'=>$node.'/'.$f, 'qtip'=>'', 'cls'=>'file','leaf'=>true);
        }
    }
    $d->close();
    echo $json->encode($nodes);
} else
if ($sAction==ACTION_VIEW) {
    $sUserName = fn_getParam("strUserName","");

    $sql = "SELECT USERNAME,TRUENAME,PWDQUESTION,PWDANSWER,PETNAME,HEADIMAGE,";
    $sql.= "DEPARTMENT,TITLE,SEX,BIRTHDAY,IDCARD,COUNTRY_ID,PROVINCE_ID,CITY_ID,COUNTY_ID,";
    $sql.= "HOMEADDRESS,POSTCODE,HOMEPHONE,MOBILEPHONE,QQNUMB,MSN,EMAIL,RIGHTLEVEL,";
    $sql.= "REGDATE,MODIFYDATE,HITS,LOGONNUMB,LASTLOGONDATE,LOCKSTATUS,SECURITY,REMARK ";
    $sql.= "FROM $TABLE_EP_USER ";
    $sql.= "WHERE EPID='".$sEPID."'";
    $sql.= " AND USERNAME='".$sUserName."'";
    $stmt = $DB->query($sql);
    $aUser = array();
    if ($row = $DB->fetchArray($stmt)) {
        $aUser["strUserName"]  = $row["USERNAME"];
        $aUser["strTrueName"]  = $row["TRUENAME"];
        $aUser["strPetName"]   = $row["PETNAME"];
        $aUser["strSex"]       = $row["SEX"];
        $aUser["strDepartment"]= $row["DEPARTMENT"];
        $aUser["strTitle"]     = $row["TITLE"];
        $aUser["strBirthday"]  = $row["BIRTHDAY"];
        $aUser["strAddress"]   = $row["HOMEADDRESS"];
        $aUser["strPostcode"]  = $row["POSTCODE"];
        $aUser["strTelephone"] = $row["HOMEPHONE"];
        $aUser["strMobilephone"]= $row["MOBILEPHONE"];
        $aUser["strQNumb"]     = $row["QQNUMB"];
        $aUser["strMsn"]       = $row["MSN"];
        $aUser["strEMail"]     = $row["EMAIL"];
        $aUser["strRemark"]    = $row["REMARK"];
        $aUser["strRight"]     = $row["RIGHTLEVEL"];
        $aUser["strLockStatus"]= $row["LOCKSTATUS"];
        $aUser["strSecurity"]  = $row["SECURITY"];
        $aUser["strLogonNumb"] = $row["LOGONNUMB"];
        $aUser["strLastLogonDate"]= $row["LASTLOGONDATE"];
        $aUser["strRegDate"]    = $row["REGDATE"];
        $aUser["strModifyDate"] = $row["MODIFYDATE"];
        $aUser["sCountryID"]    = $row["COUNTRY_ID"];
        $aUser["sProvinceID"]   = $row["PROVINCE_ID"];
        $aUser["sCityID"]       = $row["CITY_ID"];
        $aUser["sCountyID"]     = $row["COUNTY_ID"];
        $aUser["strHeadImg"]    = $row["HEADIMAGE"];
        //$aUser["strHeadImg"]    = str_replace("%syspath%",$CFG_VIRT_IMAGES_USER,$row["HEADIMAGE"]);
        //$aUser["strHeadImg"]    = str_replace("%userpath%",$SEC->USER_VIRT_PATH,$aUser["strHeadImg"]);
    }
    $DB->freeResult($stmt);
    if ($sRole == RIGHT_USER && $SEC->sUserName!=$sUserName) { //not admin
        $sSECURITY = fn_str_split($aUser["strSecurity"]);
        if (!fn_getSecViewRight($sSECURITY[0],$sRelation)) $aUser["strBirthday"] = "0000-00-00"; //birthday
        if (!fn_getSecViewRight($sSECURITY[1],$sRelation)) {$aUser["strAddress"] = $sMark; $aUser["strPostcode"]=$sMark;} //address
        if (!fn_getSecViewRight($sSECURITY[2],$sRelation)) $aUser["strTelephone"] = $sMark; //联系电话
        if (!fn_getSecViewRight($sSECURITY[3],$sRelation)) $aUser["strMobilephone"] = $sMark; //手机号码
        if (!fn_getSecViewRight($sSECURITY[4],$sRelation)) $aUser["strQNumb"] = $sMark; //QQ号码
        if (!fn_getSecViewRight($sSECURITY[5],$sRelation)) $aUser["strMsn"]   = $sMark; //MSN ADD.
        if (!fn_getSecViewRight($sSECURITY[6],$sRelation)) $aUser["strEMail"] = $sMark; //EMAIL ADD.
    }
    
    echo $json->encode(array('success'=>true,'total'=>"1",'data'=>$aUser));
    unset($aUser);
    return;
} else
if ($sAction==ACTION_INSERT || $sAction==ACTION_UPDATE) { 
    $sUserName     = fn_getParam("strUserName","");
    $sPassword     = fn_getParam("strPassword","");
    $sTrueName     = fn_getParam("strTrueName","");
    $sPetName      = fn_getParam("strPetName","");
    $sDepartment   = fn_getParam("strDepartment","");
    $sTitle        = fn_getParam("strTitle","");
    $sSex          = fn_getParam("strSex","");
    $sBirthday     = fn_getParam("strBirthday","");
    $sHeadImg      = fn_getParam("strHeadImg","");
    $sCountryID    = fn_getParam("strCountryID","");
    $sProvinceID   = fn_getParam("strProvinceID","");
    $sCityID       = fn_getParam("strCityID","");
    $sCountyID     = fn_getParam("strCountyID","");
    $sAddress      = fn_getParam("strAddress","");
    $sPostcode     = fn_getParam("strPostcode","");
    $sTelephone    = fn_getParam("strTelephone","");
    $sMobilephone  = fn_getParam("strMobilephone","");
    $sQQNumb       = fn_getParam("strQQNumb","");
    $sMSN          = fn_getParam("strMSN","");
    $sEMail        = fn_getParam("strEMail","");
    $sSecurity     = fn_getParam("strSecurity","");
    $sRight        = fn_getParam("strRight","");
    $sLockStatus   = fn_getParam("strLockStatus","0");
    $sRemark       = fn_getParam("strRemark","");

    $sSuccess = true;
    $sErrMesg = "";
    if ($sRight == RIGHT_ADMIN) {
        $sql = "SELECT COUNT(1) FROM ".$TABLE_EP_USER;
        $sql.= " WHERE EPID='".$sEPID."' AND RIGHTLEVEL='".$sRight."' AND USERNAME<>'".$sUserName."'";
        if ($DB->getFirstField($sql) >= 2) {
            $sSuccess = false;
            $sErrMesg = "只能设定2个管理员，不能再添加管理员！";
        }
    }
    if ($sAction == ACTION_INSERT && $sErrMesg=="") {  //insert new user
        $sql = "SELECT COUNT(1) FROM ".$TABLE_EP_USER;
        $sql.= " WHERE EPID='".$sEPID."' AND USERNAME='".$sUserName."'";
        if ($DB->getFirstField($sql) > 0) {
            $sSuccess = false;
            $sErrMesg = "该用户名 ".$sUserName." 已经存在，不能重复添加！";
        } else {
            if ($sRight == "") {
                $sRight = RIGHT_USER;
            }

            $sql = "INSERT INTO $TABLE_EP_USER(EPID,USERNAME,TRUENAME,PASSWD,PETNAME,";
            $sql.= "COUNTRY_ID,PROVINCE_ID,CITY_ID,COUNTY_ID,DEPARTMENT,";
            $sql.= "TITLE,SEX,BIRTHDAY,HOMEADDRESS,POSTCODE,";
            $sql.= "HOMEPHONE,MOBILEPHONE,QQNUMB,MSN,EMAIL,";
            $sql.= "RIGHTLEVEL,REGDATE,SECURITY,REMARK) ";
            $sql.= "VALUES('".$sEPID."','".$sUserName."','".$sTrueName."',md5('".$sPassword."'),'".$sPetName."','";
            $sql.= $sCountryID."','".$sProvinceID."','".$sCityID."','".$sCountyID."','".$sDepartment."','";
            $sql.= $sTitle."','".$sSex."','".$sBirthday."','".$sAddress."','".$sPostcode."','";
            $sql.= $sTelephone."','".$sMobilephone."','".$sQQNumb."','".$sMSN."','".$sEMail."','";
            $sql.= $sRight."',now(),'".$sSecurity."','".$sRemark."')";
            $DB->query($sql);
            //echo 'right1:'.$sRight;
            $sErrMesg = '用户注册成功';
        }
    } else if ($sAction == ACTION_UPDATE && $sErrMesg=="") {  //update user info
        $sql = "UPDATE $TABLE_EP_USER SET ";
        $sql.= "TRUENAME='".$sTrueName."',PWDQUESTION='',PWDANSWER='',PETNAME='".$sPetName."',";
        $sql.= "DEPARTMENT='".$sDepartment."',TITLE='".$sTitle."',BIRTHDAY='".$sBirthday."',";
        $sql.= "SEX='".$sSex."',HEADIMAGE='".$sHeadImg."',COUNTRY_ID='".$sCountryID."',";
        $sql.= "PROVINCE_ID='".$sProvinceID."',CITY_ID='".$sCityID."',COUNTY_ID='".$sCountyID."',";
        $sql.= "HOMEADDRESS='".$sAddress."',POSTCODE='".$sPostcode."',HOMEPHONE='".$sTelephone."',";
        $sql.= "MOBILEPHONE='".$sMobilephone."',QQNUMB='".$sQQNumb."',MSN='".$sMSN."',EMAIL='".$sEMail."',";
        if ($sRight != "") {
            $sql.= "RIGHTLEVEL='".$sRight."',";
        }
        if ($sLockStatus != "") {
            $sql.= "LOCKSTATUS='".$sLockStatus."',";
        }
        $sql.= "SECURITY='".$sSecurity."',MODIFYDATE=now(),REMARK='".$sRemark."' ";
        $sql.= "WHERE EPID='".$sEPID."' AND USERNAME='".$sUserName."'";
        $DB->query($sql);
        $sErrMesg = '用户信息更改成功';
        
        if ($sUserName == $SEC->sUserName) {
            $_SESSION["cfg_true_name"] = $sTrueName;
            $_SESSION['cfg_pet_name']  = $sPetName;
        }
    }
    
    echo $json->encode(array('success'=>$sSuccess,'msg'=>$sErrMesg));
} else 
if ($sAction == ACTION_DELETE) {  //delete user info
    $sUserName = fn_getParam("strUserName","");
    $conn = $DB->tconnect();
    $DB->tbegin($conn);

    $sql  = "SELECT ID FROM $TABLE_PROJECT ";
    $sql .= "WHERE EPID='".$sEPID."' ";
    $sql .= "AND USERNAME='".$sUserName."' ";
    $stmt = $DB->tquery($sql,$conn);
    while ($row = $DB->fetchRow($stmt)) {
        $sProjectID = $row["ID"];
        //delete task in first
        $sql  = "SELECT ID ";
        $sql .= "FROM $TABLE_TASK ";
        $sql .= "WHERE EPID='".$sEPID."' AND PROJECTID='".$sProjectID."'";
        $stmt2= $DB->tquery($sql,$conn);
        while ($row2 = $DB->fetchRow($stmt2)) {
            $sTaskID = $row2["ID"];
            $sql = "DELETE FROM $TABLE_TASK WHERE ID='".$sTaskID."'";
            $DB->tquery($sql,$conn);
            $sql = "DELETE FROM $TABLE_PRETASK WHERE TASKID='".$sTaskID."'";
            $DB->tquery($sql,$conn);
            $sql = "DELETE FROM $TABLE_TASK_RESOURCE WHERE TASKID='".$sTaskID."'";
            $DB->tquery($sql,$conn);
        }
        $DB->freeResult($stmt2);
    }
    $DB->freeResult($stmt);
    //delete project
    $sql = "DELETE FROM $TABLE_PROJECT WHERE EPID='".$sEPID."' ";
    $sql .= "AND USERNAME='".$sUserName."'";
    $stmt = $DB->tquery($sql,$conn);
    
    //delete message
    $sql  = "SELECT ID,MESSAGEID FROM $TABLE_MAIL ";
    $sql .= "WHERE EPID='".$sEPID."' ";
    $sql .= "AND USERNAME='".$sUserName."'";
    $stmt= $DB->tquery($sql,$conn);
    while ($row = $DB->fetchRow($stmt)) {
        $sMailID = $row["ID"];
        $sMessageID = $row["MESSAGEID"];
        $sql = "SELECT COUNT(ID) FROM $TABLE_MAIL WHERE MESSAGEID='".$sMessageID."'";
        $iMailCount = $DB->getFirstField($sql);
        if ($iMailCount == 1) { //剩下最后一个时，则将内容删除
            $sql = "DELETE FROM $TABLE_MAIL_CONTENT WHERE ID='".$sMessageID."'";
            $DB->tquery($sql,$conn);
        }
    }
    $DB->freeResult($stmt);
    $sql = "DELETE FROM $TABLE_MAIL ";
    $sql .= "WHERE EPID='".$sEPID."' ";
    $sql .= "AND USERNAME='".$sUserName."' ";
    $DB->tquery($sql,$conn);

    //delete user
    $sql = "DELETE FROM $TABLE_EP_USER ";
    $sql .= "WHERE EPID='".$sEPID."' ";
    $sql .= "AND USERNAME='".$sUserName."' ";
    $DB->tquery($sql,$conn);
    $DB->tcommit($conn);
    $DB->tclose($conn);
    echo $json->encode(array('success'=>true,'msg'=>"用户及其相关信息已经成功删除!"));
}
else if ($sAction=="initPwd") {
    $sUserName = fn_getParam("strUserName2","");
    $sPassword = fn_getParam("strPassword2","");
    $sNewPwd   = fn_getParam("strNewPwd","");
    $sRandCode = strtoupper(fn_getParam("strRandCode",""));
    $randCode  = $_SESSION["pwdVerifyCode"];

    if ($sRandCode == $randCode) {
        $sql = "UPDATE $TABLE_EP_USER SET PASSWD='".md5($sNewPwd);
        $sql .= "' WHERE EPID='".$sEPID."' ";
        $sql .= "AND USERNAME='".$sUserName."' ";
        if ($sPassword != '') {
            $sql .= "AND PASSWD='".md5($sPassword)."'";
        }
        $DB->query($sql);
        if ($DB->affectedRows() > 0) {
            echo $json->encode(array('success'=>true,'msg'=>"新密码设置成功!"));
        } else {
            echo $json->encode(array('success'=>false,'msg'=>"旧密码错误，新密码设置失败!"));
        }
    } else {
        echo $json->encode(array('success'=>false,'msg'=>"验证码输入错误!"));
    }
}
?>